package com.breaktian.network.http;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;

/**
 * Created by keke.tian on 2018/4/3.
 */

public class HttpClient {
    private static OkHttpClient mOkHttpClient;

    static OkHttpClient init(HttpConfig httpConfig){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        build(httpConfig,builder);
        mOkHttpClient = builder.build();
        return mOkHttpClient;
    }

    private static void build(HttpConfig httpConfig, OkHttpClient.Builder builder) {
        if(httpConfig==null){
            httpConfig = HttpConfig.getInstance();
        }

        builder.connectTimeout(httpConfig.connectTimeout, TimeUnit.SECONDS);
        builder.writeTimeout(httpConfig.writeTimeout,TimeUnit.SECONDS);
        builder.readTimeout(httpConfig.readTimeout,TimeUnit.SECONDS);

        if (httpConfig.isDebug) {
            builder.addNetworkInterceptor(new LoggingInterceptor());
        }

        if (!httpConfig.interceptors.isEmpty()) {
            for (Interceptor interceptor : httpConfig.interceptors) {
                builder.addInterceptor(interceptor);
            }
        }
        if (!httpConfig.networkInterceptors.isEmpty()) {
            for (Interceptor interceptor : httpConfig.networkInterceptors) {
                builder.addNetworkInterceptor(interceptor);
            }
        }
        if (httpConfig.sslSocketFactory != null && httpConfig.trustManager != null) {
            builder.sslSocketFactory(httpConfig.sslSocketFactory, httpConfig.trustManager);
        }
        if (httpConfig.hostnameVerifier != null) {
            builder.hostnameVerifier(httpConfig.hostnameVerifier);
        }
    }

    static OkHttpClient getInstance(){
        if(mOkHttpClient==null){
            synchronized (HttpClient.class){
                if(mOkHttpClient==null){
                    init(HttpConfig.getInstance());
                }
            }
        }
        return mOkHttpClient;
    }


}
